<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Copy;
use App\Models\Area;
use App\Models\Order;
use App\Models\DoctorWorks;
use App\Models\OrderGoods;
use App\Util\Url;
use Doctrine\DBAL\Exception\DatabaseDoesNotExist;
use Encore\Admin\Auth\Database\Administrator;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use App\Admin\Extensions\CheckDrawMoney;
use App\Util\Tool;
use http\Client\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;
use phpDocumentor\Reflection\DocBlock\Description;
use Encore\Admin\Widgets\Table;
use App\User;

/**
 * 此项目由百凯伦公司研发，后面省略一万字
 */
class OrderController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商品订单管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new Order());

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete(); //禁止行级删除路由
        });
        $grid->disableExport();//禁止导出
        $grid->filter(function ($filter) {
//            // 去掉默认的id过滤器
//            $filter->disableIdFilter();
//            // 在这里添加字段过滤器
//            //电话	姓名	商品名称	状态	订单编号	开始时间-截止时间
            $filter->equal('orderaddress.phone', __('电话'));
            $filter->like('orderaddress.name', __('姓名'));
            $filter->like('order_goods.goods_name', __('商品名称'));
            $filter->equal('receive_status', "收货状态")->select([0 => '未收货', 1 => "已收货"]);
            $filter->equal('evaluate_status', "评价状态")->select([0 => '未评价', 1 => "已评价"]);
            $filter->equal('order_status', "订单状态")->select([0 => '未完成', 1 => "已完成", 2 => "申请售后", 3 => "售后完成", 4 => "取消订单"]);
            $filter->equal('sn', __('订单编号'));
            $filter->between('created_at', '订单时间')->datetime();
        });

        $grid->disableCreateButton();//禁用创建按钮
        $userid = auth()->user()->id ?? 0;
        $is_work = auth()->user()->is_work;
        if($is_work >0){
            $where [] = ['work_id', '=', $is_work];//工作室
            $where [] = ['order_type', '=', 2];//商品类型
            $where [] = ['order_source', '=', 1];//商品类型
        }else{
            $where [] = ['suppliers_id', '=', $userid];//供应商
            $where [] = ['order_source', '=', 2];//商品类型
        }
        $grid->model()->where($where)->orderByDesc('id');//只查看审核过的商品
        $grid->fixColumns(0, 1);//固定列可滑动列表
        $grid->column('id', __('Id'));
        $grid->column('order_goods', __('商品名称'))->display(function () {
            return $this->order_goods->goods_name ?? '';
        });
        //评价
        $grid->column('order_evaluate', '订单评价')->expand(function ($model) {
            $comments = $model->getEvaluate()->take(1000)->where([['types', '=', 2]])->orderBy('id', 'desc')->get()->map(function ($comment) {
                $comment->user_id = $comment->user()->first()->name ?? '';
                return $comment->only(['id', 'user_id', 'content', 'created_at']);
            });
            return new Table(['ID', '评论用户', '评论内容', '发布时间'], $comments->toArray());
        });

        $grid->column('order_goods_pic', __('商品图片'))->display(function () {
            if (!empty($this->order_goods->goods_img)) {
                return Url::getHttpHost() . 'upload/' . $this->order_goods->goods_img;
            }
        })->lightbox(['width' => 50, 'height' => 50]);

        $grid->column('product_standard', __('商品规格'))->display(function () {
            return $this->order_goods->product_standard ?? '';
        });
        $grid->column('sn', __('订单编号'));
        $grid->column('remarks', __('订单备注'))->limit(20)->ucfirst()->editable();
        $grid->column('orderaddress.name', __('收货人姓名'));
        $grid->column('orderaddress.phone', __('联系方式'));
        $grid->column('order_delivery_addr', __('详细地址'))->display(function () {
            $area = new Area();
            $province_name = $area->where('code', $this->orderaddress->province_id ?? 0)->value('name');
            $city_name = $area->where('code', $this->orderaddress->city_id ?? 0)->value('name');
            $district_name = $area->where('code', $this->orderaddress->district_id ?? 0)->value('name');
            $detail = $this->orderaddress->detail ?? '';
            return $province_name . '->' . $city_name . '->' . $district_name . '<br/>->' . $detail;
        });
        $grid->column('nums', __('商品数量'));
        $grid->column('created_at', __('创建时间'));
        $grid->column('delivery_status', __('是否发货'))->using([
            0 => '未发货',
            1 => '已发货',
        ])->dot([
            0 => 'danger',
            1 => 'success',
        ]);
        $grid->column('receive_status', __('是否收货'))->using([
            0 => '未收货',
            1 => '已收货',
        ])->dot([
            0 => 'danger',
            1 => 'success',
        ]);
        $grid->column('pay_type', __('支付方式'))->using([
            0 => '未支付',
            1 => '微信',
            2 => '支付宝',
            3 => '余额',
            4 => '代付',
        ])->dot([
            0 => 'danger',
            1 => 'success',
            2 => 'success',
            3 => 'success',
            4 => 'success',
        ]);
        $grid->column('pay_status', __('支付状态'))->using([
            0 => '未支付',
            1 => '已支付',
        ])->dot([
            0 => 'danger',
            1 => 'success',
        ]);
        $grid->column('pay_time', __('支付时间'));
        $grid->column('order_status', __('订单状态'))->using([
            0 => '未完成',
            1 => '已完成',
            2 => '申请售后',
            3 => '售后完成',
            4 => '取消订单',
        ])->dot([
            0 => 'danger',
            1 => 'success',
            2 => 'warning',
            3 => 'success',
            4 => 'info',
        ]);
        $grid->column('is_invoice', __('是否已开发票'))->using([
            0 => '未开',
            1 => '已开',
        ])->dot([
            0 => 'danger',
            1 => 'success',
        ]);
        $grid->column('total_price', __('订单总价格'));
        $grid->column('created_at', __('创建时间'));
        Admin::css('

.fa-edit:before, .fa-pencil-square-o:before {
    content: "发货" !important;
}
.fa {
    content: "发货";

}
        ');
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Order::findOrFail($id));
        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();
            $tools->disableEdit();
        });
        $show->field('id', __('Id'));
        $show->field('sn', __('订单号'));
        $show->field('created_at', __('创建时间'));
        $show->field('remarks', __('订单备注'));
        $show->field('pay_time', __('支付时间'));
        $show->field('orderaddress.name', __('收货人姓名'));
        $show->field('orderaddress.phone', __('联系方式'));
        $show->field('order_delivery_addr', __('收货地址'))->as(function () {
            $area = new Area();
            $province_name = $area->where('code', $this->orderaddress->province_id ?? 0)->value('name');
            $city_name = $area->where('code', $this->orderaddress->city_id ?? 0)->value('name');
            $district_name = $area->where('code', $this->orderaddress->district_id ?? 0)->value('name');
            $detail = $this->orderaddress->detail ?? '';
            return $province_name . '->' . $city_name . '->' . $district_name . '->' . $detail;
        });
        $show->field('order_goods', __('商品名称'))->as(function () {
            return $this->order_goods->goods_name ?? '';
        });
        $show->field('order_goods_pic', __('商品图片'))->as(function () {
            if (!empty($this->order_goods->goods_img)) {
                return Url::getHttpHost() . 'upload/' . $this->order_goods->goods_img;
            }
        })->image(['width' => 100, 'height' => 100]);
        $show->field('product_standard', __('商品规格'));
        $show->field('logis_company', __('物流公司名称'));
        $show->field('logis_num', __('物流单号'));
        $show->field('delivery_status', __('是否发货'))->as(function () {
            $option = [
                0 => '未发货',
                1 => '已发货'
            ];
            return $option[$this->delivery_status] ?? '';
        });
        $show->field('receive_status', __('是否收货'))->as(function () {
            $option = [
                0 => '未收货',
                1 => '已收货'
            ];
            return $option[$this->receive_status] ?? '';
        });

        $show->field('pay_type', __('支付方式'))->as(function () {
            $option = [
                0 => '未支付',
                1 => '微信',
                2 => '支付宝',
                3 => '余额',
                4 => '代付'
            ];
            return $option[$this->pay_type] ?? '';
        });
        $show->field('pay_status', __('支付状态'))->as(function () {
            $option = [
                0 => '未支付',
                1 => '已支付'
            ];
            return $option[$this->pay_status] ?? '';
        });
        $show->field('order_status', __('订单状态'))->as(function () {
            $option = [
                0 => '未完成',
                1 => '已完成',
                2 => '申请售后',
                3 => '售后完成',
                4 => '取消订单'
            ];
            return $option[$this->order_status] ?? '';
        });

        $show->field('is_invoice', __('是否开发发票'))->as(function () {
            $option = [
                0 => '未开',
                1 => '已开'
            ];
            return $option[$this->is_invoice] ?? '';
        });
        $show->field('total_price', __('订单总价格'));
        $show->field('nums', __('商品数量'));
        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        //收货人姓名
        //联系方式
        //收货地址
        //订单状态
        //商品数量
        $form = new Form(new Order());
        $form->tools(function (Form\Tools $tools) {
            // 去掉`删除`按钮
            $tools->disableDelete();
        });

        $form->text('sn', __('订单号'))->readonly();
        $form->text('orderaddress.name', __('收货人姓名'));
        $form->mobile('orderaddress.phone', __('联系方式'));
        $form->distpicker(['orderaddress.province_id', 'orderaddress.city_id', 'orderaddress.district_id'], '请选择区域');
        $form->text('orderaddress.detail', __('收货地址'));
        $form->textarea('remarks', __('订单备注'));
        /**
         *  `logis_company` varchar(100) DEFAULT NULL COMMENT '物流公司名称',
         * `   logis_num` varchar(30) NOT NULL DEFAULT '0' COMMENT '物流单号',
         * `   logis_code` varchar(100) DEFAULT NULL COMMENT '物流编码',
         */
        $form->select('logis_code', '物流公司名称')->options(Tool::logis_code());//->rules('required');
        $form->text('logis_num', __('物流单号'));
        $form->saving(function (Form $form) {
            $logis_code = Request()->logis_code ?? '';
            $logis_num = Request()->logis_num ?? '';
            if (!empty($logis_code)) {
                $form->model()->setAttribute('logis_company', Tool::logis_code()[$logis_code] ?? '');//
                if (!empty($logis_code) && !empty($logis_num)) {
                    $delivery_time = $form->model()->getAttribute('delivery_time');
                    if ($delivery_time == '' || $delivery_time == null) {
                        $form->model()->setAttribute('delivery_time', date("Y-m-d H:i:s"));//设置发货时间
                    }
                    $form->model()->setAttribute('delivery_status', 1);//设置发货
                    $order_goods = (new OrderGoods())->where([['order_id','=',$form->model()->id]])->first();
//                    推送消息
                    $dt["user_id"] = $form->model()->user_id;
                    $dt["title"] = "发货通知";
                    $dt["content"] = "您购买的".$order_goods->goods_name."商品已发货，由".$form->model()->logis_company."物流配送，订单号：".$form->model()->sn."。";
                    Tool::startPush($dt);
                }
            }
        });
//        $form->decimal('order_price', __('Order price'));
//        $form->decimal('pay_price', __('Pay price'));
//        $form->decimal('total_price', __('Total price'));
//        $form->decimal('logis_price', __('Logis price'));
//        $form->switch('pay_type', __('Pay type'));
//        $form->switch('order_type', __('Order type'));
//        $form->datetime('pay_time', __('Pay time'))->default(date('Y-m-d H:i:s'));
//        $form->switch('pay_status', __('Pay status'));
//        $form->switch('order_status', __('Order status'));
//        $form->switch('delivery_status', __('Delivery status'));
//        $form->datetime('delivery_time', __('Delivery time'))->default(date('Y-m-d H:i:s'));
//        $form->switch('receive_status', __('Receive status'));
//        $form->datetime('receive_time', __('Receive time'))->default(date('Y-m-d H:i:s'));
//        $form->number('evaluate_status', __('Evaluate status'));
//        $form->datetime('evaluate_time', __('Evaluate time'))->default(date('Y-m-d H:i:s'));

        return $form;
    }
}
